import numpy as np
import pandas as pd

img = pd.read_csv('./imgs_new.csv').values
Dbis = pd.read_csv('./Dbis.csv').values
img = img[:,1:513]
Dbis = Dbis[:,1:513]
bins = [1, 3, 3, 4, 4, 6, 6, 7, 250, 250, 250, 250, 250, 250, 250, 250]
print(img.shape)
row,col = img.shape

flag =0



def recover(img_data,ec,flags,bins,Dbis):
    row,col = img_data.shape
    secrect = np.zeros((1,row*col))[0]
    index =0
    for i in range(1,row-2):
        for j in range(1,col-2):
            v1 = int(img[i - 1][j])
            v2 = int(img[i][j - 1])
            v3 = int(img[i + 1][j])
            v4 = int(img[i][j + 1])
            four_neighbor = np.array(
                [int(v1), int(v2), int(v3), int(v4)])
            p = int(np.ceil(np.average(four_neighbor)))
            em = int(img[i][j]) - int(p)
            if np.mod(i+j,2) == 0 and flags == 0 and ec>0:
                ks = Dbis[i][j] - 1
                if int(em) == bins[int(ks)] or int(em)  == -bins[int(ks)] - 1:
                    ec=ec - 1
                    secrect[index] = 0
                    index += 1
                if int(em)  == bins[int(ks)]+1 or int(em)  == -bins[int(ks)] - 2:
                    ec=ec - 1
                    print(i, j)
                    secrect[index] = 1
                    index += 1
            if np.mod(i + j, 2) == 1 and flags == 1 and ec>0:
                ks = Dbis[i][j] - 1
                if int(em)  == bins[int(ks)] or int(em)  == -bins[int(ks)] - 1:
                    # secrect[i][j] = 0
                    secrect[index] = 0
                    ec - 1
                    index += 1
                if int(em)  == bins[int(ks)] + 1 or int(em)  == -bins[int(ks)] - 2:
                    # secrect[i][j] = 1
                    secrect[index] = 1
                    ec - 1
                    index += 1
    return secrect

a=recover(img,5106,0,bins,Dbis)
pd.DataFrame(a).to_csv('./recover.csv')
print(a)